﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietPublisher.Web.Framework;
using VietPublisher.BaseProject.Models;
using VietPublisher.BSL.BK;
using VietPublisher.FileManager;

namespace VietPublisher.Web.BK.Controllers
{
    public class BookController : StringBaseEntityController
    {
        //
        // GET: /Book/
         [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Index()
        {
            return View();
        }

        [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult BookList()
        {
            List<ListBook> books = RepoBook.GetBooks();
            return View("List_Book", books);
        }

        //
        //Get top book in slide show
        public ActionResult TopBookList()
        {
            List<ListBook> books = RepoBook.GetTopBooks(12);
            return View("User_SlideBooks", books);
        }



        //
        // GET: /Book/Create
        [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Create()
        {
            var model = new T_BK_Book();

            return View(model);
        }

        //
        // POST: /Book/Create

        [HttpPost, CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Create(T_BK_Book collection)
        {

            try
            {

                //step 1: get more infomation
                var AuthorGroupID = Request.Form["AuthorGroupID"] != "" ? Request.Form["AuthorGroupID"].ToString() : ",0";
                AuthorGroupID = AuthorGroupID.Substring(1);
                var PublisherID = Request.Form["PublisherID"] != "" ? Request.Form["PublisherID"].ToString() : ",0";
                PublisherID = PublisherID.Substring(1);
                var CategoryID = Request.Form["CategoryID"] != "" ? Request.Form["CategoryID"].ToString() : ",0";
                CategoryID = CategoryID.Substring(1);
                //step 2: add AuthorGroup to get id AuthorGroup
                var authorGrpId = RepoAuthor.AddAuthorGrp(AuthorGroupID);

                //step 3: set information to Collection T_BK_book
                collection.AuthorGroupID = authorGrpId;
                collection.PublisherID = int.Parse(PublisherID);
                collection.CategoryID = int.Parse(CategoryID);

                //step 4: add new Book or Update and finish
                if (collection.BookID != 0)
                {
                    RepoBook.BookUpdate(collection);
                }
                else
                {
                    RepoBook.CreateBook(collection);
                }


                // TODO: Add insert logic here

                return RedirectToAction("Create");
            }
            catch (Exception e)
            {
                LogUtility.LogMessage("Book", "Create", e.Message);
                return RedirectToAction("Create");
            }
        }

        //
        // GET: /Book/Edit/5
        [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Edit(int id)
        {
            //step 1 :get book
            var Book = RepoBook.GetBookByBookID(id);
            //step 2: get 4 viewData
            var authors = RepoAuthor.GetAuthorList(Book.AuthorGroupID ?? 0);
            ViewData["Author"] = authors;

            ViewData["GroupIdImage"] = Book.PictureID;

            var category = RepoCategory.GetCategoryByBookID(id);
            category = category ?? new T_BK_Category();
            var categoryList = new List<T_BK_Category>(){
               category
            };
            ViewData["Category"] = categoryList;

            var publisher = RepoPublisher.GetPublisherByBook(id);
            publisher = publisher ?? new T_BK_Publisher();
            var publisherList = new List<T_BK_Publisher>(){
               publisher
            };
            ViewData["Publisher"] = publisherList;
            //step 3 : return view
            return View("Create", Book);
        }

        //
        // POST: /Book/Edit/5

        [HttpPost, CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Book/Delete/5
        [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Book/Delete/5

        [HttpPost, CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        /// <summary>
        /// use session be writen at Author/SessionAuthorSave
        /// minh moi nay ra y tuong. ko chay len server. neu nhu set dc client qua client thi sao?. co li lam chu. se rat la le
        /// </summary>
        /// <returns></returns>
        //public ActionResult LoadDivAuthor()
        //{
        //    //todo [Triet] load div when save form popup author at Book.add
        //    return PartialView("_AuthorDiv");
        //}


        public ActionResult LoadImage()
        {
            int GroupIdImage = 0;
            GroupIdImage = Request.Params["GroupIdImage"] != null ? int.Parse(Request.Params["GroupIdImage"].ToString()) : 0;
            ViewData["GroupIdImage"] = GroupIdImage;
            return PartialView("_BookUploadImage");

        }
        [HttpPost, CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult submitImage(FormCollection collection)
        {
            int idGroupReturn = 0;
            var file = Request.Files["pic"];
            if (file != null)
            {
                byte[] buf = new byte[file.ContentLength];
                file.InputStream.Read(buf, 0, file.ContentLength); //do stuff with the bytes 
                var Image = new ImageHandler();
                idGroupReturn = Image.WriteToFile(buf, file.FileName);
            }
            ViewData["idGroupReturn"] = idGroupReturn;
            return View("ResultChooseImage");
        }

        [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult OpenPopupChooseImage()
        {
            return View();
        }

        [CustomAuthorize(Roles = SiteRoles.Admin)]
        public ActionResult ResultChooseImage()
        {
            return View();
        }


    }
}
